﻿/**
 * Author:chzhcpu@gmail.com
 *  
*/
using System;
using System.Collections.Generic;
using System.Web;
using HtmlAgilityPack;
using System.Threading;
using System.IO;

/// <summary>
///espPatentGrabber 的摘要说明
/// </summary>
public class espPatentGrabber:Task
{
    private string pn = "";

    private string host = "http://worldwide.espacenet.com";
    private string dlhost = "http://worldwide.espacenet.com/espacenetDocument.pdf?flavour=plainPage&";
    private string dochost = "http://worldwide.espacenet.com/publicationDetails/originalDocument?";
    private string srhost = "http://worldwide.espacenet.com/searchResults?DB=EPODOC&submitted=true&locale=en_EP&ST=number&compact=false&NUM=";

    public espPatentGrabber(string pn = "WO2007120936")
	{
		//
		//TODO: 在此处添加构造函数逻辑
        this.pn = pn;
	}
    public override void SearchbyPN(Object stateInfo)
    {
        string pnpath = AppDomain.CurrentDomain.BaseDirectory + "PatentFiles\\" + pn + "\\";

        string shost =srhost+ pn;
        string prog = "";
        if (File.Exists(pnpath + pn + ".pdf"))
        {
            this.FireProgressChangedEvent(pn, "完成进度：100%");
            return;
        }
        if (!Directory.Exists(pnpath))
        {
            Directory.CreateDirectory(pnpath);
        }
        try
        {
            string html = UtilsList.GetHtmlPage(shost);
            HtmlDocument hdoc = new HtmlDocument();
            hdoc.LoadHtml(html);
            HtmlNode titleNode = hdoc.DocumentNode.SelectSingleNode("//span[@class='resNumber']/a");
            string records = hdoc.DocumentNode.SelectSingleNode("//div[@class='modSearchResult']").InnerHtml;
            string titleurl = titleNode.GetAttributeValue("href", "#");
            string docparam = titleurl.Split(new char[] { '?' })[1];
            html = UtilsList.GetHtmlPage((dochost + docparam).Replace("&amp;", "&"));
            hdoc.LoadHtml(html);
            int pagenum = hdoc.DocumentNode.SelectNodes("//select[@id='navigationSelector']/option").Count;

            //删除最后一个文件，以防下载不完整
            UtilsList.DeleteLatestFile(pnpath);

            for (int i = 0; i < pagenum; i++)
            {
                string pdfdlurl = dlhost + docparam + "&pageNumber=" + (i + 1).ToString();
                pdfdlurl = pdfdlurl.Replace("&amp;", "&");
                
                if (File.Exists(pnpath + pn + i + ".pdf"))
                {
                    continue;
                    /*if (UtilsList.GetLocalFileLength(pnpath + pn + i + ".pdf")
                        < UtilsList.GetRemoteFileLength(pdfdlurl))
                        continue;
                    else
                    {
                        File.Delete(pnpath + pn + i + ".pdf");
                        UtilsList.DownloadFile(pnpath + pn + i + ".pdf", pdfdlurl);
                    }*/
                }
                else
                {
                    UtilsList.DownloadFile(pnpath + pn + i + ".pdf", pdfdlurl);
                }
                this.FireProgressChangedEvent(pn,
                    "下载进度：" + ((i + 1.0) / pagenum * 100).ToString("F1") + "%"
                    );
            }
            if (!File.Exists(pnpath + pn + ".pdf"))
            {
                PDFGenetor.CombinePdf(pnpath, pnpath + pn + ".pdf");
            }
            prog = "完成进度：100%";
        }
        catch (Exception ex)
        {
            prog = ex.Message; //throw ex;
        }
        this.FireProgressChangedEvent(pn, prog);

        return ;
    }
}